import httpInstance from "@/utils/http";


// 调用注册接口的函数，请求参数格式：x-www-form-urlencoded
export const registerAPI = (registerData) => {
  // registerData为对象
  // 借助于UrlSearchParams对象，将请求参数对象转换为查询字符串
  const registerDataStr = new URLSearchParams()
  for (let key in registerData) {
    registerDataStr.append(key, registerData[key])
  }
  // 源代码
  // return httpInstance.post(
  //   '/user/register',
  //   registerDataStr
  // )

  // 优化代码
  return httpInstance({
    url: '/user/register',
    method: 'POST',
    data: registerDataStr
  })
}

// 登录接口
export const loginAPI = (loginData) => {
  const loginDataStr = new URLSearchParams()
  for (let key in loginData) {
    loginDataStr.append(key, loginData[key])
  }

  return httpInstance({
    url: '/user/login',
    method: 'POST',
    data: loginDataStr
  })
}


// 获取用户信息接口
export const getUserInfoAPI = () => {
  return httpInstance({
    url: '/user/userInfo'
  })
}

// 修改用户信息接口
export const updateUserInfoAPI = (data) => {
  return httpInstance({
    url: '/user/update',
    method: 'PUT',
    data
  })
}

// 修改用户头像
export const updateUserAvatarAPI = (avatarUrl) => {
  // 请求参数格式 queryString
  const data = new URLSearchParams()
  data.append('avatarUrl', avatarUrl)

  return httpInstance({
    url: '/user/updateAvatar',
    method: 'PATCH',
    data
  })
}
